package aaaCms;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

//import org.apache.commons.collections4.map.ListOrderedMap;






import com.attilax.core;
import com.attilax.atian.PinyinX;
import com.attilax.fdb.ColsGener;
import com.attilax.fdb.FdbX;
import com.attilax.formatter.FormatterEasyuiImp;
import com.attilax.index.IndexManager;
import com.attilax.index.IndexStoreService;
import com.attilax.io.dirx;
import com.attilax.io.filex;
import com.attilax.io.pathx;
import com.attilax.lang.Closure;
import com.attilax.lang.Closure2;
import com.attilax.lang.MapX;
import com.attilax.lang.ParamX;
import com.attilax.lang.SerialUtil;
import com.attilax.lang.YamlAtiX;
import com.attilax.text.strUtil;
import com.attilax.util.PropX;
import com.attilax.util.numUtil;
import com.attilax.util.timeTester;

/**
 * { 'application_type': null, 'update_user': null, 'detail': '',
 * 'can_down_org': '', 'file_path': '动作类\\三日刺杀\\三日刺杀.mkv', 'material_type': 3,
 * 'effectie_time': null, 'txt_file': 'uploadfiles/动作类/三日刺杀/三日刺杀.txt',
 * 'material_keyword': 'srcs', 'material_id': 8604, 'director': null,
 * 'logicDel': null, 'size': '', 'material_description': '三日刺杀', 'staring':
 * null, 'update_time': null, 'play_time': 0, 'special_id': null, 'create_time':
 * null, 'create_user': null, 'thumb': 'images/p4.jpg', 'failure_time': null }
 * 
 * @author Administrator
 *
 */
// aaaCms.CmsImpLocalFileVer.list
// aaaCms.CmsImpLocalFileVer.list_ori
@SuppressWarnings("all")
public class CmsImpLocalFileVer2 extends CmsImpLocalFileVer {

	public static String maindir = "z:/";
//	protected String table;
	protected ColsGener colsGener;
	

	public static void main(String[] args) {
		
		
	}
	
	public String envi;
	
	public List query_post(String string) {
		final Map sql = MapX.newMap();
		sql.put("op", "select");
		sql.put("table", maindir);
		   

		sql.put("cols", colsGener);

		FdbX fx = new FdbX();
		Object list = fx.exe(sql);
		return (List) list;
		
	}

	

	public Object get_post_intro(Object txt_url) {
		String t = filex.read("z:/" + txt_url, "gbk");
		return t;

	}

	public Object get_posts(Object paramsMap) {
		Map m=(Map) paramsMap;
		final Map sql = MapX.newMap();
		sql.put("op", "select");
		sql.put("cols", colsGener);
		sql.put("table", maindir);
		
		Map m2=MapX.newMap();
		m2.put("cate", m.get("cate"));
		sql.put("where", m2);

		FdbX fx = new FdbX();
		Object list = fx.exe(sql);
		return (List) list;
	 

	}

	/**
	 * id zeush mkv path
	 * 
	 * @param id
	 * @return
	 */
	public Object get_post(Object id) {

		Map mv = new HashMap();
		String resDir = (String) id;
		resDir = "z:/" + resDir;
		resDir = new File(resDir).getParent();
		mv.put("file_path", getFileName(resDir));
		mv.put("thumb", getPicName(resDir));
		mv.put("txt_file", getTxtName(resDir));
		String mov_name = new File((String) id).getParentFile().getName();
		mv.put("material_description", mov_name);

		return mv;

	}

	public Object get_post_api(Object id) {

		if (numUtil.isNum(id)) {
			PropX px = new PropX(pathx.classPathParent_jensyegeor()
					+ "/index_movs.txt", "gbk");
			id = px.getProperty((String) id);
		}
		Map m = (Map) get_post(id);
		List<Map> movs = new ArrayList<Map>();
		movs.add(m);
		return core.toJsonStrO88(FormatterEasyuiImp.fmtList(movs));

	}

	/**
	 * with cache
	 * 
	 * @param obj
	 * @return
	 */
	public Object list(Object obj) {

		Map m = new ParamX().urlParams2Map(obj.toString());
		String cate_id = (String) m.get("param");

		List<Map> movs = list_cache(cate_id);

		System.out.println("--get movs size:" + movs.size());
		return core.toJsonStrO88(FormatterEasyuiImp.fmtList(movs));
	};

	public Object list_nocache(String cate_id) {
		// =params;
		List<Map> movs = list_ori(cate_id);
		System.out.println("--get movs size:" + movs.size());
		String jsonStrO88 = core.toJsonStrO88(FormatterEasyuiImp.fmtList(movs));
		filex.saveLog(jsonStrO88, "C:\\jsonx");
		return jsonStrO88;
	}

	public String getCateid(String f) {
		String f_relate = f;
		if (f.contains(":")) // thumb format
		{
			int startIdx = maindir.length();

			try {
				f_relate = f.substring(startIdx);
			} catch (Exception e) {
				System.out.println("");
			}
		}
		String[] a = f_relate.split("/");
		String cate = a[0].trim();
		// a[1 + new CmsImpLocalFileVer().getOffsetlen()];
		String s = pathx.classPathParent_jensyegeor() + "/cate.txt";
		Map m = YamlAtiX.getMapReverse(s);
		String cateid = (String) m.get(cate);
		return cateid;

	}

	public Object lastMap4dbg;

	private List<Map> list_cache(final String cate_id) {
		String cateIndexDir = pathx.classPathParent_jensyegeor()
				+ "/index_movs/cateIndexs";
		Closure indexGener = new Closure() {

			@Override
			public Object execute(Object arg0) throws Exception {
				IndexManager im = new IndexManager(
						pathx.classPathParent_jensyegeor() + "/index_movs");
				List<Map> li = getitemNameList_fullinfo();
				im.createIndex("cateIndexs", "col", li, new Closure2() {

					@Override
					public Object execute(Object arg0) {
						Map map = (Map) arg0;
						String f = (String) map.get("file_path");
						if (f == null || f.trim().length() == 0) // should use
																	// file as
																	// index
																	// ,,use
																	// thumb
																	// only for
																	// debug
							f = (String) map.get("thumb");
						// d:/z/爱情类/K歌情人/K歌情人.jpg==f
						lastMap4dbg = map;
						String cate_id = getCateid(f);
						if (cate_id == null) // if file thumb all empty then
												// empty
							System.out.println("dbg");
						return cate_id;
					}
				});
				return null;
			}
		};
		Closure noIndexDataGener = new Closure() {

			@Override
			public Object execute(Object arg0) throws Exception {

				List<Map> list_ori = list_ori(cate_id);
				Map m = new HashMap();
				m.put(cate_id, list_ori);

				return m;
			}
		};
		Map index = (Map) getDatas(cateIndexDir, indexGener, noIndexDataGener);

		return (List<Map>) index.get(cate_id);
	}

	private Object getDatas(String cateIndexDir, final Closure indexGener,
			Closure noIndexDataGener) {
		Object itemNameList = new ArrayList<Map>();
		final String index_file1 = cateIndexDir + "/1.txt";
		final String idx_f2 = cateIndexDir + "/2.txt";
		try {
			timeTester t = new timeTester(" rad index");
			itemNameList = SerialUtil.read(index_file1);
			t.printUseTime();
			filex.saveLog(String.valueOf("read index:" + t.pasttime),
					"c:\\time");
			System.out.println(" use index :" + index_file1);
		} catch (Exception e) {
			try {

				itemNameList = SerialUtil.read(idx_f2);
				System.out.println(" use index2 :" + idx_f2);

			} catch (Exception e2) {
				try {// no index
					System.out.println(" no index return noIndexDataGener");
					timeTester t = new timeTester(" ca");
					itemNameList = noIndexDataGener.execute(null);
					t.printUseTime();
					filex.saveLog("noidex" + String.valueOf(t.pasttime),
							"c:\\time");
					System.out.println("");
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				try {
					core.newThread(new Runnable() {

						@Override
						public void run() {
							Object index;
							try {
								System.out
										.println(" no index return  then gene index");
								index = indexGener.execute(null);
								new IndexStoreService().geneIndex(index,
										index_file1, idx_f2);
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
								filex.saveLog(e, "c:\\e");
							}

						}
					}, "threadName2");

				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
					filex.saveLog(e1, "c:\\e");
				}

			}

		}
		return itemNameList;
	}

	// public List<Map> list_ori_(String cate_id)
	public List<Map> list_ori(String cate_id) {
		String cate_str = getCateCnnameDir(cate_id);

		List<String> subDirs = new ArrayList<String>();
		String dirname = maindir + cate_str;
		try {

			subDirs = new dirx(dirname).subDirs();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		List<String> mov_names = subDirs;
		List<Map> movs = new ArrayList<Map>();
		for (String mov_name : mov_names) {
			try {
				Map mv = new HashMap();
				String resDir = dirname + "/" + mov_name;
				mv.put("file_path", getFileName(resDir));
				mv.put("thumb", getPicName(resDir));
				mv.put("txt_file", getTxtName(resDir));
				mv.put("material_description", mov_name);
				mv.put("material_id", mv.get("file_path"));

				movs.add(mv);
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		return movs;
	}

	String cate_file;

	private String getCateCnnameDir(String cate) {
		String s = pathx.classPathParent_jensyegeor() + "/cate.txt";
		cate_file = s;
		Map m = YamlAtiX.getMap(s);
		return (String) m.get(cate);
	}

	private Object getPicName(String resDir) {
		String[] list = new File(resDir).list(new FilenameFilter() {

			@Override
			public boolean accept(File paramFile, String filename) {
				// path =----filename.ext
				String extname = filex.getExtName(filename);
				if ("jpg".contains(extname) || "jpeg".contains(extname))
					return true;
				else
					return false;
			}
		});
		try {// .substring(3)
			return resDir + "/" + list[0];
		} catch (Exception e) {
			return "";
		}
	}

	private Object getTxtName(String resDir) {
		String[] list = new File(resDir).list(new FilenameFilter() {

			@Override
			public boolean accept(File paramFile, String filename) {
				// path =----filename.ext
				String extname = filex.getExtName(filename);
				if ("txt".contains(extname))
					return true;
				else
					return false;
			}
		});
		try {
			return resDir.substring(3) + "/" + list[0];
		} catch (Exception e) {
			return "";
		}
	}

	public Object getFileName(String string) {
		//
		String mvExt = ".mkv  .avi 		 .m2ts		 .ts		 .iso		 .rmvb		 .mp4";
		final Set<String> st = strUtil.toSet(mvExt, strUtil.dotChar);
		String[] list = new File(string).list(new FilenameFilter() {

			@Override
			public boolean accept(File paramFile, String filename) {
				// path =----filename.ext
				String extname = filex.getExtName(filename);
				if (st.contains(extname))
					return true;
				else
					return false;
			}
		});
		try {
			int offsetStartIndex = maindir.length();

			return string.substring(offsetStartIndex) + "/" + list[0];
		} catch (Exception e) {
			return "";
		}

	}

	public Object detail() {
		return null;
	};

	public Object search(Object obj) {
		Map mx = new ParamX().urlParams2Map(obj.toString());
		String kw = (String) mx.get("param");
		List<Map> itemNameList = new ArrayList<Map>();

		String movListssSSeriialOBjFile = pathx.classPathParent_jensyegeor()
				+ "/index_movs/searchIndex";
		itemNameList = getDatas(movListssSSeriialOBjFile);

		List<Map> movs = new ArrayList<Map>();
		for (Map m : itemNameList) {

			try {
				String kws = PinyinX.getSimple((String) m
						.get("material_description"));
				if (kws.toLowerCase().contains(kw.toLowerCase()))
					movs.add(m);
			} catch (Throwable e) {
				e.printStackTrace();
			}

		}

		movs = getFullMovsInfo(movs);

		return core.toJsonStrO88(FormatterEasyuiImp.fmtList(movs));

		// return null;
	}
/**
 * api js
 */
	public Object searchV2(Object obj) {
		// Map mx = new ParamX().urlParams2Map(obj.toString());
		String kw = (String) obj;
		List<Map> itemNameList = new ArrayList<Map>();

		String movListssSSeriialOBjFile = pathx.classPathParent_jensyegeor()
				+ "/index_movs/searchIndex";
		itemNameList = getDatas(movListssSSeriialOBjFile);

		List<Map> movs = new ArrayList<Map>();
		for (Map m : itemNameList) {

			try {
				String kws = PinyinX.getSimple((String) m
						.get("material_description"));
				if (kws.toLowerCase().contains(kw.toLowerCase()))
					movs.add(m);
			} catch (Throwable e) {
				e.printStackTrace();
			}

		}

		movs = getFullMovsInfo(movs);

		return core.toJsonStrO88(FormatterEasyuiImp.fmtList(movs));

		// return null;
	}

	/**
	 * only for search 
	 * @param movListssSSeriialOBjFile
	 * @return
	 */
	private List<Map> getDatas(String movListssSSeriialOBjFile) {
		List<Map> itemNameList;
		String index_file1 = movListssSSeriialOBjFile + "/1.txt";
		String idx_f2 = movListssSSeriialOBjFile + "/2.txt";
		try {

			itemNameList = (List<Map>) SerialUtil.read(index_file1);
		} catch (Exception e) {
			try {

				itemNameList = (List<Map>) SerialUtil.read(idx_f2);

			} catch (Exception e2) {
				// {material_description=他其实没那么喜欢你, file_path=z:/爱情类/他其实没那么喜欢你}
				itemNameList = getitemNameList();
				new IndexStoreService().geneIndex(itemNameList, index_file1,
						idx_f2);
			}

		}
		return itemNameList;
	}

	// only for
	private List<Map> getFullMovsInfo(List<Map> movs) {
		for (int i = 0; i < movs.size(); i++) {
			Map m = movs.get(i);
			try {
				// Map mv = new HashMap();
				String resDir = (String) m.get("file_path");// getSingleItemMaindir();

				m.put("thumb", getPicName(resDir));
				m.put("txt_file", getTxtName(resDir));
				m.put("file_path", getFileName(resDir));

			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		return movs;
	}

	private String getSingleItemMaindir(String f) {
		int last = f.lastIndexOf("/");
		return f.substring(0, last);
	}

	public List<Map> getitemNameList() {
		final List<Map> li = new ArrayList<Map>();
		String mov_dirs = getMovieDirs();
		dirx.traveDirPa1(mov_dirs, new Closure<String, String>() {

			@Override
			public String execute(String f) throws Exception {
				if (f.contains("@Recycle") || f.contains("player"))
					return null;
				f = pathx.fixSlash(f);
				System.out.println(f);
				String[] a = f.split(strUtil.slashChar);

				if (a.length == getSuitlen()) {
					File f2 = new File(f);
					Map m = new HashMap();
					m.put("file_path", f);
					m.put("material_description", f2.getName());
					li.add(m);
				}
				return null;
			}
		});
		return li;
	}

	public List<Map> getitemNameList_fullinfo() {
		final List<Map> li = new ArrayList<Map>();
		String mov_dirs = getMovieDirs();
		dirx.traveDirPa1(mov_dirs, new Closure<String, String>() {

			@Override
			public String execute(String f) throws Exception {
				if (f.contains("@Recycle") || f.contains("player"))
					return null;
				f = pathx.fixSlash(f);
				System.out.println(f);
				String[] a = f.split(strUtil.slashChar);

				if (a.length == getSuitlen()) {
					File f2 = new File(f);
					Map m = new HashMap();
					// m.put("file_path", f);
					m.put("material_description", f2.getName());

					String resDir = f;

					m.put("thumb", getPicName(resDir));
					m.put("txt_file", getTxtName(resDir));
					m.put("file_path", getFileName(resDir));
					li.add(m);
				}
				return null;
			}
		});
		return li;
	}

	public int getSuitlen() {

		String[] a = maindir.split("/");

		return 3 + a.length - 1;
	}

	public int getOffsetlen() {

		String[] a = maindir.split("/");

		return a.length - 1;
	}

	private String getMovieDirs() {
		// TODO Auto-generated method stub
		getCateCnnameDir("0");
		maindir = pathx.fixSlash(maindir);
		List<Map> li = YamlAtiX.getList(cate_file);
		String r = "";
		for (Map map : li) {
			r = r + "," + maindir + map.get("lab");
		}
		return r;
	};

}
